<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('客户资料列表')" />
	<th:block th:include="include :: list-css" />
	<style type="text/css">
		.importTable{empty-cells:show;border-collapse:collapse;border-spacing:0;margin-top:46px;}
		.listext th{background:#eee;color:#3366cc;}
		.listext th,.listext td{border:solid 1px #ddd;text-align:left;padding:10px;font-size:14px;}

		#importProgress {z-index:20200202;background-color: #000;opacity: 0.3;display:none;}
		.importProgress {width:300px;z-index:20202222;position: fixed;top: 34%;left: 40%;display:none;}
		.cidName {padding-right: 14px;}
		.getMore{top: 4px !important;right: 1px !important;position: absolute;cursor: pointer;background: #fff;}

		.layui-layer-title{color: #fff !important;background-color: rgba(0,135,250,0.7) !important;font-size: 17px !important;height: 51px !important;line-height: 51px !important; border-radius: 4px 4px 0 0 !important;}
	</style>
</head>
<body>
<div class="main-content">
	<div class="content-right">
		<div class="search-top">
			<span>查询条件</span>
			<a href="javascript:;" layadmin-event="flexible" class="menuBtn">
				<i class="layui-icon layui-icon-spread-left" id="LAY_app_flexible" style="color: #fff;"></i>
			</a>
		</div>
		<div class="panel layout-expand layui-expand-east">
			<div class="panel-header">
				<div class="panel-tool" style="text-align: center; width: 26px;height: 30px;line-height: 30px;">
					<a href="javascript:;" layadmin-event="flexible" class="menuBtn">
						<i class="layui-icon layui-icon-shrink-right" id="LAY_app_flexible" style="color: #fff;"></i>
					</a>
				</div>
			</div>
			<div class="panel-body panel-title" style="text-align: center; width: 26px;">查<br>询<br>条<br>件</div>
		</div>
		<form class="layui-form">
			<th:block th:include="listinclude :: searchRight('page')" />
		</form>
	</div>
	<div class="mid-content">
		<table class="layui-hide" id="dhtable" lay-filter="ftable"></table>
	</div>
</div>
<!-- 表格头部工作栏-->
<script type="text/html" id="toolbar">
	<div class="layui-btn-container">
		<div class="layui-btn layui-btn-normal layui-table-tools" style="background: rgba(0,161,21,1) !important;" onclick="newTab('/crm/customer/add','客户资料 - 新增')" shiro:hasPermission="crm:customer:add">
			<p class="dhicon dh-lujing1089" style="color:white;font-size:14px"><span class="fa_span">新增</span></p>
		</div>
		<div class="layui-btn layui-btn-warm layui-table-tools" onclick="shift()" shiro:hasPermission="crm:customer:edit">
			<p class="dhicon dh-zu4246_1" style="color:white;font-size:14px"><span class="fa_span">批量转移</span></p>
		</div>
		<div th:if="${session.mandatorUser.userLevel >= 6}" class="layui-btn layui-btn-danger layui-table-tools" onclick="newTab('/crm/customer/recover','客户资料(已删除)')" shiro:hasPermission="crm:customer:cancel">
			<p class="dhicon dh-zu4133_12" style="color:white;font-size:14px"><span class="fa_span">回收站</span></p>
		</div>
		<div th:if="${session.mandatorUser.userLevel >= 6}" class="layui-btn layui-table-tools" onclick="newTab('/crm/customertransfer','客户资料(转移记录)')">
			<p class="dhicon dh-zu4851" style="color:white;font-size:14px"><span class="fa_span">转移记录</span></p>
		</div>
		<div class="layui-btn layui-table-tools" onclick="newTab('/crm/customerpersion','客户资料(联系人)')">
			<p class="dhicon dh-zu4855" style="color:white;font-size:14px"><span class="fa_span">联系人</span></p>
		</div>
		<div class="layui-btn layui-table-tools importbtn-bg" lay-event="importBtn" shiro:hasPermission="crm:customer:import">
			<i class="dhicon dh-zu4499_1"></i> 导入
		</div>
		<div class="layui-btn layui-table-tools importbtn-bg" lay-event="exportbtn" shiro:hasPermission="crm:customer:export">
			<i class="dhicon dh-zu5116"></i> 导出
		</div>
	</div>
</script>
<!-- 表格操作区 -->
<script type="text/html" id="barDh">
	{{# if(d.gClient!='BXS'){ }}
	{{# if(d.bUser=='[[${session.mandatorUser.userId}]]' || [[${session.mandatorUser.userLevel}]]>=6){ }}
	<a class="layui-btn layui-btn-xs dhicon dh-edit" onclick="newTab('/crm/customer/edit?gClient={{d.gClient}}','客户资料({{d.gClient}}) - 修改')" shiro:hasPermission="crm:customer:edit">&nbsp;编辑</a>
	<a class="layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove" onclick="remove('{{d.gClient}}')" shiro:hasPermission="crm:customer:delete">&nbsp;删除</a>
	<a class="layui-btn layui-btn-warm layui-btn-xs dhicon dh-exchange" onclick="shift('{{d.gClient}}')" shiro:hasPermission="crm:customer:edit">&nbsp;转移</a>
	<a class="layui-btn layui-btn-warm layui-btn-xs dhicon dh-random" onclick="share('{{d.gClient}}')" shiro:hasPermission="crm:customer:edit" style="background-color: #5cb85c">&nbsp;共享</a>
	{{# }else{ }}
	<a class="layui-btn layui-btn-xs layui-btn-warm dhicon dh-search" onclick="newTab('/crm/customer/edit?canntEdit=1&gClient={{d.gClient}}','客户资料({{d.gClient}})-详情')">&nbsp;详情（共享客户）</a>
	{{# } }}
	{{# }else{ }}
	<a class="layui-btn layui-btn-xs layui-btn-warm dhicon dh-search" onclick="newTab('/crm/customer/edit?canntEdit=1&gClient={{d.gClient}}','客户资料({{d.gClient}})-详情')">&nbsp;详情（备货客户）</a>
	{{# } }}
</script>
<!-- 客户导入区域 -->
<script type="text/template" id="importTpl">
	<form enctype="multipart/form-data" class="mt20 mb10">
		<div class="col-xs-offset-1">
			<input type="file" id="file" name="file"/>
			<div class="mt10 pt5">
				<a onclick="$.tablelist.importTemplate('/crm/customer/exporttemplate')" class="btn btn-default btn-xs"><i class="dhicon dh-file-excel-o"></i> 下载模板</a>
			</div>
			<font color="red" class="pull-left mt10">
				提示：仅允许导入“xls”或“xlsx”格式文件！
			</font>
		</div>
	</form>
</script>
<!-- 导入明细 -->
<div id="iTable" class="display_no">
	<form class="layui-form" style="position: fixed;width: 800px;background: #fff;">
		<div class="layui-form-item" style="margin:5px 0 0;">
			<div class="layui-inline layui-col-md3" style="width: 31%;">
				<label class="layui-form-label"><font class="f_red">*</font>所属公司：</label>
				<div class="layui-input-block">
					<input type="text" class="layui-input buttontext cidName" onclick="getMoreForImport('company')" readonly>
					<input type="hidden" class="cid">
					<i class="layui-icon layui-icon-more getMore" onclick="getMoreForImport('company')"></i>
				</div>
			</div>
			<div class="layui-inline layui-col-md3" style="width: 31%;">
				<label class="layui-form-label"><font class="f_red">*</font>所属员工：</label>
				<div class="layui-input-block">
					<input type="text" class="layui-input buttontext bUserName" onclick="getMoreForImport('user')" readonly>
					<input type="hidden" class="bUser">
					<input type="hidden" class="bDept">
					<i class="layui-icon layui-icon-more getMore" onclick="getMoreForImport('user')"></i>
				</div>
			</div>
			<div class="layui-inline layui-col-md3" style="width: 31%;">
				<label class="layui-form-label"><font class="f_red">*</font>客户属性：</label>
				<div class="layui-input-block">
					<select name="stepName" th:with="type=${@baseinfosimple.getBaseInfoSimpleData('khsx')}">
						<option value="">请选择</option>
						<option th:each="dict : ${type}" th:text="${dict.vname}" th:value="${dict.vid}" th:selected="${dict.vid} eq ${customerInfo?.stepName}"></option>
					</select>
				</div>
			</div>
		</div>
	</form>
	<table class="importTable listext" data-resizable-columns-id="demo-table">
		<tbody id="itbody"></tbody>
	</table>
</div>
<!-- 导入进度条 -->
<div id="importProgress" class="layui-layer-shade"></div>
<div class="importProgress">
	<div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="dhprogress">
		<div class="layui-progress-bar layui-bg-blue" lay-percent="0%"></div>
	</div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />
<th:block th:include="include :: searchJS" />
<th:block th:include="listinclude :: list-templeat" />
<script th:inline="javascript">
	/*<![CDATA[*/
	var prefix = ctx + "crm/customer",
			gridColumns = [[${gridColumns}]],
			importFields =[[${importFields}]],
			moduleTable =[[${moduleTable}]];
	/*]]>*/
</script>
<script type="text/javascript">
	var element,thStr;
	var fieldWidth = {},		//导入列表字段宽度
			filedRequired = {},		//导入列表必填字段
			dateFiled = [],			//导入列表日期字段
			hasNull = false;		//导入数据必填字段有空值
	$.each(gridColumns.dictionaryForPageFieldList,function(i,v){
		fieldWidth[v.fields] = v.fieldFrontWidth;
		if(v.fieldFrontRequired)filedRequired[v.fields] = v.fieldName;
		if(v.fieldFrontType == 't_date')dateFiled.push(v.fields);
	})
	var $,layer,form,table,wherestr={};
	layui.use(['table','form','layer','jquery','element'], function () {
		$ = layui.$,layer = layui.layer,form = layui.form,table = layui.table, element = layui.element;
		serachRender();//查询条件初始渲染集合
		$.tablelist.init({
			elem: '#dhtable'
			,modalName: "客户资料"
			,url: prefix + '/list?deleted=0'
			,totalRow: gridColumns.totalRow
			,cols: [gridColumns.gridBody
			]
			,toolbar: '#toolbar'
			,defaultToolbar: [{title:'列设置',layEvent: 'fieldSet',icon: 'layui-icon-set'}] //这里在右边显示
			,height:'full-36'
		});
		//监听排序事件
		table.on('sort(ftable)', function(obj){
			$.tablelist.sort('dhtable',obj);
		});
		//监听开关动作
		form.on('switch(change)', function(obj){
			var data={};
			data['gClient']=obj.value;
			if(obj.elem.checked==true){
				data[obj.elem.name]=1;
				$.operate.post(prefix + "/editpost", {'customerInfoItems':JSON.stringify([data])});
				if(obj.elem.name=="bShared")$.operate.post(prefix + "/deleteshared", {'gClient':obj.value});
			}else{
				data[obj.elem.name]=0;
				$.operate.post(prefix + "/editpost", {'customerInfoItems':JSON.stringify([data])});
			}
		});
		//头工具栏事件
		table.on('toolbar(ftable)', function(obj){
			switch(obj.event){
				case 'exportbtn':
					$.ajax({
						url: prefix + '/export?deleted=0',
						type: 'GET',
						data: getWherestr(),
						dataType: 'json',
						beforeSend: function(){
							showloadings(true);
						},
						success: function(result){
							if(result.code == 0) {
								window.location.href = ctx + "common/download?fileName=" + encodeURIComponent(result.msg) + "&delete=" + true;
								parent.$('.page-loading').hide();//页面进行了跳转刷新，需要手动关闭页面的加载动画
							}else if(result.code == web_status.WARNING) {
								$.modal.alertWarning(result.msg)
							}else{
								$.modal.alertError(result.msg);
							}
							showloadings(false);
						}
					});
					break;
				case 'tableFull'://表格展开
					$('.north .layui-form').hide();
					table.reload('dhtable',{
						defaultToolbar: [{title:'收缩',layEvent:'tableShrink',icon:'layui-icon-screen-restore'}],
						height: $(window).height()-$('.north').height()-60<300?'300':$(window).height()-( $('.north').height()+$('.south').height()+12)
					});
					break;
				case 'tableShrink'://表格收缩
					$('.north .layui-form').show();
					table.reload('dhtable',{
						defaultToolbar: [{title:'展开',layEvent:'tableFull',icon:'layui-icon-screen-full'}],
						height: $(window).height()-$('.north').height()-60<300?'300':$(window).height()-( $('.north').height()+$('.south').height()+12)
					});
					break;
				case 'importBtn':
					thStr = '<tr><th><div style="width:30px;">序号</div></th>'
					$.each(importFields,function(i,val){
						fieldWidth[val] = fieldWidth[val]?fieldWidth[val]:100;			//默认宽度100px
						thStr += '<th><div style="width:'+fieldWidth[val]+'px;">' + i + '</div></th>';
					})
					thStr += '</tr>';
					layer.open({
						type: 1,
						area: ['400px', '230px'],
						fix: false,
						offset: '10%',
						maxmin: true,
						shade: 0.3,
						title: '导入客户',
						content: $('#importTpl').html(),
						btn: ['<i class="dhicon dh-check"></i> 导入', '<i class="dhicon dh-remove"></i> 取消'],
						shadeClose: true,
						zIndex: 1000,
						btn1: function(index, layero){
							var file = layero.find('#file');
							if(!file[0]['value']){
								layer.msg("请选择文件！");
								return false;
							}
							var imRes = importListExcel(file[0], importFields, 'customer');
						}
					});
					break;
				case 'fieldSet':
					filedSet(moduleTable);
					break;
			};
		});
	});
	//通过guid假性删除
	function remove(gClient){
		$.operate.remove("确定要删除么？",prefix + "/editpost",{'customerInfoItems':JSON.stringify([{'gClient':gClient,'deleted':1}])},function(result){
			if(result.code==0){
				setTimeout(function(){
					layer.closeAll();
					table.reload('dhtable');
				}, 1000);
			}
		});
	}
	//打开新标签
	function newTab(url,title){
		if(top.layui.index)top.layui.index.openTabsPage(url,title);
		else window.open(url);
	}
	//弹出层——共享
	function share(gClient){
		$.modal.open($.tablelist._option.modalName+"（"+gClient+"） - 共享", prefix +"/editshared?gClient="+gClient,'1000');
	}
	//弹出层——转移
	function shift(gClient){
		if(gClient){
			$.modal.open($.tablelist._option.modalName+" - 转移", prefix +"/editbuser?gClient="+gClient);
		}else{
			if(table.checkStatus('dhtable').data==''){
				layer.msg('请至少选择一名要转移的客户！', {icon: 7,anim:6});
			}else{
				var bxsFlag=false;//判断是否勾选备货客户
				$.each(table.checkStatus('dhtable').data,function(i,v){
					if(v.gClient=="BXS")bxsFlag=true;
				})
				if(bxsFlag)layer.msg('备货客户无法转移！', {icon: 7,anim:6});
				else $.modal.open($.tablelist._option.modalName+" - 转移", prefix +"/editbuser");
			}
		}
	}
	/*批量请求导入数据
     *tobj：导入数据对象
     *startNum：从第几条开始导入
     *oneImportNum：每次导入条数
     *allImportNum：总数据量
     *times：导入次数
     */
	var cID = bUser = bDept = stepName = '';
	function eachImport(tobj,startNum, oneImportNum, allImportNum, times, timeNum){
		var importObj = [], inum = startNum, importBl='0%', res;
		for(var i = startNum; i < startNum + oneImportNum; i++){
			if(i >= allImportNum)break;
			inum = i + 1 ;
			tobj[i]['cID'] = cID; tobj[i]['bUser'] = bUser; tobj[i]['bDept'] = bDept; tobj[i]['stepName'] = stepName;
			importObj.push(tobj[i]);
		}
		$.ajaxSettings.async = false;
		$.post(prefix+ "/importpost", {'customerInfoItems':JSON.stringify(importObj, null, 2)}, function(result) {
			importBl = (inum/allImportNum)*100;
			console.log('导入比:'+importBl.toFixed(2)+ '%');
			console.log('数量:'+inum);
			console.log('总次数:'+times);
			console.log('当前次数:'+timeNum);
			importObj = [];
			timeNum += 1;
			res = result;
		},"json");
		setTimeout(function(){
			if(timeNum <= times){
				eachImport(tobj, startNum + oneImportNum, oneImportNum, allImportNum, times, timeNum);
			}else{
				element.progress('dhprogress', importBl.toFixed(2)+ '%');
				showloadings(false);
				closeProcess(res, 'customer');
			}
			element.progress('dhprogress', importBl.toFixed(2)+ '%');
		},500);
	}
</script>
</body>
</html>